import { Form, Button, Upload, Input, Image, Switch } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { useState } from "react";
import { addBanner } from "./../../../api/banner";

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};

const AddBanner = (props) => {
  const [url, setUrl] = useState("");

  const normFile = (e) => {
    if (e.fileList[0]) {
      console.log(e);
      console.log("上传", e.file);
      const reader = new FileReader();
      reader.onloadend = (e) => {
        setUrl(e.target.result);
      };
      reader.readAsDataURL(e.file); //把图片转换成base64位格式
      return e && e.fileList;
    }
  };
  const onFinish = (values) => {
    console.log(values);
    values.bannerimg = values.bannerimg[0].thumbUrl;
    console.log(111);
    addBanner(values).then((res) => {
      console.log("res", res);
        props.history.go(0);
    });
  };

  //阻止图片的默认上传
  const beforeUpload = (picture) => {
    // setUrl(e.fileList[0].thumbUrl);
    return false;
  };
  return (
    <Form name="validate_other" {...formItemLayout} onFinish={onFinish}>
      <Form.Item
        {...formItemLayout}
        name="bannertitle"
        label="轮播图标题"
        rules={[
          {
            required: true,
            message: "请输入轮播图标题",
          },
        ]}
      >
        <Input placeholder="请输入轮播图的标题" />
      </Form.Item>
      <Form.Item
        {...formItemLayout}
        name="link"
        label="link"
        rules={[
          {
            required: true,
            message: "请输入轮播图链接地址",
          },
        ]}
      >
        <Input placeholder="请输入轮播图链接地址" />
      </Form.Item>
      <Form.Item
        name="isshow"
        label="轮播图状态"
        valuePropName="checked"
        rules={[
          {
            required: false,
            message: "请输入轮播图状态",
          },
        ]}
      >
        <Switch />
      </Form.Item>
      <Form.Item
        name="bannerimg"
        label="上传图片"
        valuePropName="fileList"
        getValueFromEvent={normFile}
        rules={[
          {
            required: true,
            message: "请选择轮播图片",
          },
        ]}
      >
        <Upload name="logo" listType="picture" beforeUpload={beforeUpload}>
          <Button icon={<UploadOutlined />}>Click to upload</Button>
          {/* <Image src={ url } /> */}
        </Upload>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          span: 12,
          offset: 6,
        }}
      >
        <Image src={url} />
      </Form.Item>

      <Form.Item
        wrapperCol={{
          span: 12,
          offset: 6,
        }}
      >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};
export default AddBanner;
